/**
 * Copyright (c) 2018-2022, NXOS Development Team
 * SPDX-License-Identifier: Apache-2.0
 * 
 * Contains: NX_Thread context 
 * 
 * Change Logs:
 * Date           Author            Notes
 * 2021-10-16     JasonHu           Init
 */

#include <base/context.h>
#include <base/memory.h>
#include <base/log.h>
#include <base/irq.h>
#include <arch/context.h>
#include <arch/sysregs.h>

#define INITIAL_SPSR_EL1 (PSTATE_EL1 | SP_ELx)

NX_IMPORT void NX_HalContextSwitchNext(NX_Addr nextSP);
NX_IMPORT void NX_HalContextSwitchPrevNext(NX_Addr prevSP, NX_Addr nextSP);

NX_PRIVATE void *NX_HalContextInit(void *startEntry, void *exitEntry, void *arg, void *stackTop)
{
    NX_HalTrapFrame *stk;

    stk = (NX_HalTrapFrame *)(((NX_U8 *)stackTop - sizeof(NX_HalTrapFrame)));

    stk->cpsr = INITIAL_SPSR_EL1;
    stk->pc = (NX_U64)startEntry;

    /* return task's current stack address */
    return (void *)stk;
}

NX_INTERFACE struct NX_ContextOps NX_ContextOpsInterface = 
{
    .init           = NX_HalContextInit,
    .switchNext     = NX_HalContextSwitchNext,
    .switchPrevNext = NX_HalContextSwitchPrevNext,
};
